<?php
/**
 * Created by PhpStorm.
 * User: yu
 * Date: 2017/1/11
 * Time: 下午2:36
 */

namespace Home\Controller;


use Common\Controller\HomeController;
use Common\Model\AddressModel;
use Common\Model\OrderListModel;
use Common\Model\OrderModel;

class OrderController extends HomeController
{
	//显示订单列表
	public function lists(){
		//订单数据
		$orderData = isset($_SESSION['orderList']) ? $_SESSION['orderList'] : [];
		p($orderData);
		$this->assign('orderData',$orderData);

		//地址数据
		$addressData = (new AddressModel())->where("uid={$_SESSION['user']['uid']}")->select();
		$this->assign('addressData',$addressData);
		p($orderData);
		$this->display();
	}

	/**
	 * 将购物车数据写入session并跳转到 结算页面
	 */
	public function addOrder(){
		//模拟登录
		$_SESSION['user']['uid'] = 1;
		if(!isset($_SESSION['user']['uid'])){
			redirect(u('home/login/login'));
		}
		if(!isset($_POST['cartId'])){
			$this->error('请选择要结算商品');die;
		}
		//要结算订单的商品数据
		$orderData = [];
		foreach ($_POST['cartId'] as $k=>$v){
			$orderData['order'][$v] = $_SESSION['cart']['goods'][$v];
		}
		//订单总价及 货品总数
		$orderData['totalPrice'] = 0;
		$orderData['totalNum'] = 0;
		foreach ($orderData['order'] as $k=>$v){
			$orderData['totalPrice'] += $v['total'];
			$orderData['totalNum'] += $v['num'];
		}
		$_SESSION['orderList'] = $orderData;
		//重定向
		redirect(u('home/order/lists'));die;
	}

	/**
	 * 生成订单，并创建订单列表
	 */
	public function createOrder(){
		$uid = $_SESSION['user']['uid'];
		$address = (new AddressModel())->where("uid=$uid and status=1")->find();
		$data = [
			'number'=>date('YmdHis').mt_rand(0,9999),
			'consignee'=>$address['uaname'],
			'address'=>$address['province'].$address['city'].$address['block'].$address['detail'],
			'mobile'=>$address['phone'],
			'total'=>$_SESSION['orderList']['totalPrice'],
			'time'=>time(),
			'remark'=>'',
			'uid'=>$uid
		];
		$re = (new OrderModel())->store($data);
		$oid = $re['data'];//获得订单表主键id

		foreach ($_SESSION['orderList']['order'] as $k=>$v){
			$orderList = [
				'quantity' => $v['num'],
				'subtotal' => $v['total'],
				'explain'=> implode('-',$v['options']),
				'gid'=>$v['id'],
				'oid'=>$oid,
				'glid'=>$v['glid'],
				'glnumber'=>$v['glnumber']
			];
			(new OrderListModel())->store($orderList);
			unset($_SESSION['cart']['goods'][$k]);
		}
		unset($_SESSION['orderList']);
		echo 1;die;

	}
}